package com.atguigu.ggkt.vod.service.impl;

import com.atguigu.ggkt.vo.vod.*;
import com.atguigu.ggkt.model.vod.Course;

import com.atguigu.ggkt.model.vod.CourseDescription;
import com.atguigu.ggkt.model.vod.Subject;
import com.atguigu.ggkt.model.vod.Teacher;
import com.atguigu.ggkt.vod.mapper.CourseMapper;
import com.atguigu.ggkt.vod.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

//import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author sleephardzz
 * @since 2023-07-10
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    //    @ApiOperation("获取所有课程列表")
    @Override
    public List<Course> findList() {
        List<Course> courseList = baseMapper.selectList(null);
        courseList.stream().forEach(i -> {
            this.getTeacherOrSubjectName(i);
        });
        return courseList;
    }
    //条件查询带分页
    @Override
    public Map<String, Object> findPageCourse(Page<Course> page,
                                              CourseQueryVo courseQueryVo) {
        //1获取条件值
        String title = courseQueryVo.getTitle();
        Long sId = courseQueryVo.getSubjectId();/** 第二层 */
        Long sPId = courseQueryVo.getSubjectParentId();/** 第一层 */
        Long tId = courseQueryVo.getTeacherId();
        //2判断条件为null，封装查询条件：
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(sId)) {
            wrapper.eq("subject_id", sId);
        }
        if (!StringUtils.isEmpty(sPId)) {
            wrapper.eq("subject_parent_id", sPId);
        }
        if (!StringUtils.isEmpty(tId)) {
            wrapper.eq("teacher_id", tId);
        }
//        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(!StringUtils.isEmpty(title), Course::getTitle, title);
//        wrapper.eq(!StringUtils.isEmpty(sId), Course::getSubjectId, sId);
//        wrapper.eq(StringUtils.isEmpty(sPId), Course::getSubjectParentId, sPId);
//        wrapper.eq(StringUtils.isEmpty(tId),Course::getTeacherId, tId);


        //3调用方法实现条件查询
        Page<Course> conditionPage = baseMapper.selectPage(page, wrapper);
        long pageTotal = conditionPage.getTotal();//总记录数
        long pages = conditionPage.getPages();//总页数
        long currentPage = conditionPage.getCurrent();//当前页
        long size = conditionPage.getSize();//每页记录数
        List<Course> records = conditionPage.getRecords();//**每页数据集合

        /** 需要进一步封装List<Course>-course.getParam()  遍历封装讲师和分类名称 */
        records.stream().forEach(r -> {
            this.getNameById(r);
        });
        //4封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", pageTotal);
        map.put("totalPage", pages);
        map.put("records", records);
        return map;
    }

    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseDescriptionService courseDescriptionService;

    //课程添加
    @Override
    public Long saveCourseInfo(CourseFormVo courseFormVo) {
        //1课程分类表
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        baseMapper.insert(course);
        //2课程描述表
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseFormVo.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionService.save(courseDescription);
        return course.getId();
    }

    //获取课程分类
    @Override
    public CourseFormVo getCourseInfoById(Long id) {
        //课程分类
        Course course = baseMapper.selectById(id);
        if (course == null)
            return null;
        //课程信息
        CourseDescription courseDescription = courseDescriptionService.getById(id);
//            return null;
        //封装
        CourseFormVo courseFormVo = new CourseFormVo();
        BeanUtils.copyProperties(course, courseFormVo);
//        BeanUtils.copyProperties(course, courseDescription);
        if (courseDescription != null)
            courseFormVo.setDescription(courseDescription.getDescription());
        return courseFormVo;
    }

    //修改课程信息
    @Override
    public void updateCourseByCourseFormVo(CourseFormVo courseFormVo) {
        //修改课程分类
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        baseMapper.updateById(course);
        //TODO:修改了描述信息，没有修改课程id
        //修改描述信息
        CourseDescription courseDescription = courseDescriptionService.getById(course.getId());
        courseDescription.setDescription(courseFormVo.getDescription());
        courseDescription.setId(course.getId());//新增
        courseDescriptionService.updateById(courseDescription);
    }

    //根据课程id查询发布课程信息
    @Override
    public CoursePublishVo getCoursePublishVo(Long id) {
        /** 自定义语句，关联三张表，查询： */
        CoursePublishVo coursePublishVo = baseMapper.selectCoursePublishVoById(id);
        return coursePublishVo;
    }

    //发布课程
    @Override
    public void publishCourse(Long id) {
        Course course = baseMapper.selectById(id);
        /** 修改发布信息 */
        course.setStatus(1);
        course.setPublishTime(new Date());
        baseMapper.updateById(course);
    }

    @Autowired
    private VideoService videoService;
    @Autowired
    private ChapterService chapterService;

    //删除课程byId
    @Override
    public void removeCourseById(Long id) {
        //删除小节 TODO 小节中包含的视频也需要删掉
        videoService.removeVideoByCourseId(id);
        //删除章节
        chapterService.removeChapterByCourseId(id);
        //删除描述
        courseDescriptionService.removeById(id);
        //删除课程本身
        baseMapper.deleteById(id);
    }

    ////根据课程分类【course】查询课程列表【分页状】
    @Override
    public Map<String, Object> findPage(IPage<Course> pageParam, CourseQueryVo courseQueryVo) {
        //获取条件值

        //判断条件值，然后封装
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        //名称//二级分类//一级分类//讲师
        wrapper.eq(!StringUtils.isEmpty(courseQueryVo.getTitle()), Course::getTitle, courseQueryVo.getTitle())
                .eq(!StringUtils.isEmpty(courseQueryVo.getSubjectId()), Course::getSubjectId, courseQueryVo.getSubjectId())
                .eq(!StringUtils.isEmpty(courseQueryVo.getSubjectParentId()), Course::getSubjectParentId, courseQueryVo.getSubjectParentId())
                .eq(!StringUtils.isEmpty(courseQueryVo.getTeacherId()), Course::getTeacherId, courseQueryVo.getTeacherId());
        //调用方法进行条件分页查询
        IPage<Course> pages = baseMapper.selectPage(pageParam, wrapper);
        //获取数据
        long totalCount = pages.getTotal();//总记录数
        long totalPage = pages.getPages();//总页数
        long currentPage = pages.getCurrent();//当前页
        long size = pages.getSize();//每页记录数
        List<Course> records = pages.getRecords();//每页数据集合
        //封装
        records.stream().forEach(r -> {
            this.getTeacherOrSubjectName(r);
        });
        //map集合返回
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", totalCount);
        map.put("totalPage", totalPage);
        map.put("records", records);
        return map;
    }

    private Course getTeacherOrSubjectName(Course course) {
        //讲师名称
        Teacher teacher = teacherService.getById(course.getTeacherId());
        if (teacher != null) {
            course.getParam().put("teacherName", teacher.getName());
        }

        //课程分类名
        //一级分类名
        Subject subjectOne = subjectService.getById(course.getSubjectParentId());
        if (subjectOne != null) {
            course.getParam().put("subjectParentTitle", subjectOne.getTitle());
        }
        //二级分类名
        Subject subjectTwo = subjectService.getById(course.getSubjectId());
        if (subjectTwo != null) {
            course.getParam().put("subjectTitle", subjectTwo.getTitle());
        }
        return course;
    }

    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private TeacherService teacherService;//操作讲师

    //根据课程id查询课程详情
    @Override
    public Map<String, Object> getInfoById(Long courseId) {
        //浏览数量view_count+1
        Course course = baseMapper.selectById(courseId);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
        //根据课程id查询Vo
        //课程详情数据
        CourseVo courseVo = baseMapper.selectCourseVoById(courseId);
        //课程分类数据：章节小节
        List<ChapterVo> chapterVoList = chapterService.getTreeList(courseId);
        //课程描述信息
        CourseDescription courseDescription = descriptionService.getById(courseId);
        //课程所属讲师信息
        Teacher teacher = teacherService.getById(course.getTeacherId());
        //封装到map集合
        Map<String, Object> map = new HashMap<>();
        //TODO后续完善
        Boolean isBuy = false;

        map.put("courseVo", courseVo);
        map.put("chapterVoList", chapterVoList);
        map.put("description", null != courseDescription ?
                courseDescription.getDescription() : "");
        map.put("teacher", teacher);
        map.put("isBuy", isBuy);//是否购买
        return map;
    }


    //    @Autowired
//    private TeacherService teacherService;//操作讲师
    @Autowired
    private SubjectService subjectService;//操作课程类型

    private Course getNameById(Course course) {
        //1讲师id查询
        Teacher teacher = teacherService.getById(course.getId());
        if (teacher != null) {
            /** 通过父类的Param */
            course.getParam().put("teacherName", teacher.getName());
        }
        //2课程分类id查询
        Subject subjectOne = subjectService.getById(course.getSubjectParentId());
        if (subjectOne != null) {
            course.getParam().put("subjectParentTitle", subjectOne.getTitle());
        }
        Subject subjectTwo = subjectService.getById(course.getSubjectId());
        if (subjectTwo != null) {
            course.getParam().put("subjectTitle", subjectTwo.getTitle());
        }
        return course;
    }
}
